#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib-object.h>
/*
 * gpiomon -r 0 24
 * */
#include "gpiod.h"
void *gpiod_edge_thread(int num, int offset, int *value_p)
{
  //int old = 0, new = 0;
  struct gpiod_chip *chip = NULL;
  struct gpiod_line *line = NULL;

  chip = gpiod_chip_open_by_number(num);
  if (!chip) {
    printf("err, L%d\n", __LINE__);
    return NULL;
  }
  line = gpiod_chip_get_line(chip, offset);
  if (!line) {
    printf("L%d\n", __LINE__);
    return NULL;
  }
  line = gpiod_chip_get_line(chip, offset);
  if (!line) {
    printf("request output\n");
    return NULL;
  }
  if (gpiod_line_request_rising_edge_events(line, "EdgeCounter") < 0) {
    printf("Failed to request rising edge events\n");
    gpiod_chip_close(chip);
    return NULL;
  }
  int edge_count = 0;
  while (1) {
    struct gpiod_line_event event;
    if (gpiod_line_event_wait(line, NULL) < 0) {
      printf("Error while waiting for event");
      break;
    }
    if (gpiod_line_event_read(line, &event) < 0) {
      printf("Error while reading event");
      break;
    }
    if (event.event_type == GPIOD_LINE_EVENT_RISING_EDGE) {
      edge_count++;
      *value_p = edge_count;
      printf("Rising edge detected! Count[%d]: %d\n",
          offset, edge_count);
    }
  }
  return NULL;
}
int main (int argc, char **argv)
{
  printf("Usage: gpioedge [num] [offset]");
  int num = 0, offset = 13, value;

  num = atoi(argv[1]);
  offset = atoi(argv[2]);
  gpiod_edge_thread(num, offset, &value);
  return 0;
}

